﻿<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MedicalManagementSystem.Models.PatientChart>" %>
<%@ Import Namespace="MedicalManagementSystem.Models" %>
<%@ Import Namespace="MedicalManagementSystem.Helpers" %>
<%@ Import Namespace="MedicalManagementSystem.Utils" %>
<div id="patientChartEdit">
    <table id="editTable" class="data_table">
    <tbody>
        <tr>
            <th>
                Диагноз
            </th>
            <th>
                Дата начала/окончания
            </th>
            <th>
                Подтверждён
            </th>
            <th>
                Действия
            </th>
            <th>
                Удалить
            </th>
        </tr>
        <%var i = 0;
          foreach (var diseaseNote in Model.Do(pch => pch.LoadDiseaseNotes()).DiseaseNotes.Each(d => d.Load()))
          {%>
        <tr>
            <td>
                <%=Html.DropDownList("blockList" + i, DiagnosBloc.DiagnosBlockDictionary, diseaseNote.Diagnos.DiagnosBloc.id, new { @class = "blockList" })%>
                <br />
                <%=Html.DropDownList("diagnosList" + i, Diagnos.GetDiagnosDictionary(diseaseNote.Diagnos.DiagnosBloc.id), 
                    diseaseNote.Diagnos.id, new { @class = "diagnosList" })%>
            </td>
            <td>
                <%=Html.TextBox("dateStart"+i, diseaseNote.DateStart.ToShortDateString(), 
                    new { @class = "dateStart" })%>
                <br />
                <%=Html.TextBox("dateEnd"+i, 
                    diseaseNote.DateEnd.HasValue ? diseaseNote.DateEnd.Value.ToShortDateString() : "", 
                    new { @class = "dateEnd" })%>
            </td>
            <td>
                <%=Html.CheckBox("confirmed" + i, diseaseNote.Confirmed.HasValue ? diseaseNote.Confirmed.Value : false,new{ @class="confirmed"})%>
            </td>
            <td>
                <a id="isClosed<%=i%>" class="isClosed">
                    <%=!diseaseNote.IsClosed ? Html.Encode("Открыть") : Html.Encode("Закрыть")%></a>
            </td>
            <td>
                <input type="button" class="deleteDiseaseNote" value="Удалить" />
            </td>
        </tr>
        <%i++;
          } %>
       </tbody>
    </table>
    <br />
    <div id="saveStatus">
        Сохранение...
    </div> 
    <div class="formErrors">
    </div>
    <div id="result">
    </div>

    <div>
        <a id="addDiseaseNote">Добавить диагноз</a> <a id="submitModel">Сохранить</a>
    </div>

    <div>
        <script language="javascript" type="text/javascript">
            var i=<%=i%>;
            <%=JSHelper.JSDictionary("diagnosBlockDict",DiagnosBloc.DiagnosBlockDictionary) %>
            $(function (){
                applyDatePicker('.dateStart','.dateEnd');
                $('#saveStatus').hide();
                $('#submitModel, #addDiseaseNote, .isClosed, .deleteDiseaseNote').button();
                $('.isClosed').trigger('click');
            });

            //------validation-----
            var formValid = true;
            $('.dateStart, .dateEnd').live('change',function(){

                var dateEndInput = $(this).parent().find('.dateEnd').removeClass('error');
                var dateStartInput = $(this).parent().find('.dateStart').removeClass('error');

                var dateEnd;
                var dateStart;
                dateStart = parseDate(dateStartInput.val());
                dateEnd = parseDate(dateEndInput.val());
                if (!dateStart) 
                    NotValidDate(dateStartInput);
                else if(!dateEnd && dateEndInput.val())
                    NotValidDate(dateEndInput);    
                else if (dateEnd && dateEnd<dateStart)
                    NotValidDate(dateStartInput , dateEndInput);
                else ValidDate();
            });
            
            function ValidDate(){
                $('#submitModel').button("enable");
                $('.formErrors').fadeOut(); 
                formValid = true;
            }

            function NotValidDate(){
                $.each(arguments, function(i,item){
                    item.addClass('error');
                });
                $('#submitModel').button( "disable" )
                $('.formErrors').text('Исправте ошибки!').fadeIn();
                formValid = false;
            }
            //-------submit--------
            function submitJsonModel() {
                if(!formValid) return;

                var diseaseNotes = [];
                $('#editTable tr:not(:first)').each(function(i,dataRow){
                       diseaseNotes.push(
                       {
                            DiagnosId : $(dataRow).find('.diagnosList').val(),
                            Confirmed : $(dataRow).find('.confirmed:checked').length != 0,
                            DateStart : $(dataRow).find('.dateStart').val(),
                            DateEnd : $(dataRow).find('.dateEnd').val()
                       });
                    }
                );
                $.ajax({
                    url: '<%=Url.Action("Edit")%>',
                    type: 'POST',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data:  JSON.stringify({id : <%=Model.id %>, DiseaseNotes : diseaseNotes}),
                    beforeSend: function()
                        {
                            $('#saveStatus').fadeIn();
                            $('#result').text("");
                        },
                    success: function(data)
                        {
                            $('#saveStatus').fadeOut(function(){
                            if (data.Successed)
                            {
                                $('#result').text("Сохранено!");
                            }
                            else
                            {
                                //TODO: implement
                            }});
                        }
                });
            };

            //------ Handlers----
            
            $('.isClosed').live('click',function(){
                var a = $(this).find('span').text(),
                    checkBoxRow = $($(this).closest('tr'));
                if ($.trim($(this).find('span').text())=="Открыть"){
                    checkBoxRow.find('.dateEnd').fadeOut().val('');
                    $(this).find('span').text('Закрыть');
                }else{
                    checkBoxRow.find('.dateEnd').fadeIn();
                    $(this).find('span').text('Открыть');
                }
            });
            
            $('.deleteDiseaseNote').live('click',removeDiseaseNote);
            $('#addDiseaseNote').click(addDiseaseNote);
            $('.blockList').live('change',getDiagnosList);
            $('#submitModel').click(submitJsonModel);

            
            function getDiagnosList() {
                var list = $(this).parent().find('.diagnosList').empty()[0].options;
                $.ajax({
                    url: '<%=Url.Action("GetListOfDiagnosis","DiagnosBloc")%>',
                    datatype: 'json',
                    data:'blockId=' + $(this).find(':selected').val(),
                    type: 'POST',
                    success: function (data){
                        $.each(
                            data.sort(lexicographicalOrder),
                            function (i,item){
                                list[i] = new Option(item.Value,item.Key);
                            }
                        );
                    }
                });
            };

            //---------generate tabel---------
            function addDiseaseNote() {
                
                i++;
                
                constructLevel()
                
                var createdRow = $('#editTable tr:last'),
                    cretedBlockList = createdRow.find('.blockList').empty()[0].options,
                    listIndex = 0;
                

                $.each(diagnosBlockDict,function(i,data){
                    if (data == undefined) return;
                    cretedBlockList[listIndex] = new Option(data, i);
                    listIndex++;
                });
                createdRow.find('.dateStart').val((new Date()).toShortDateString());
                applyDatePicker('#dateStart'+i,'#dateEnd'+i);
                $('#isClosed'+i).button();
                $('#blockList'+i).trigger('change');
                
                createdRow.fadeIn('slow');
                
                $('#isClosed'+i).trigger('click');
                
            };

            function constructLevel()
            {
                var rowDiagnos = $('<tr>');
                selectDiagnosCell().appendTo(rowDiagnos);
                inputDataCell().appendTo(rowDiagnos);
                confirmedDataCell().appendTo(rowDiagnos);
                closeCheckBox().appendTo(rowDiagnos);
                deleteButton().appendTo(rowDiagnos);
                rowDiagnos.hide().appendTo($('#editTable > tbody:last'));
            }

            function removeDiseaseNote() {
                var dataRow = $($(this).closest("tr"));
                dataRow.fadeOut('slow', function () { dataRow.remove() });
            };

             
            function selectDiagnosCell(){
                return $('<td>').append(
                    $('<select>').attr('id','blockList'+i).attr('class','blockList'),
                    $('<br>'),
                    $('<select>').attr('id','diagnosList'+i).attr('class','diagnosList')
                    );
            };
            function inputDataCell(){
                return $('<td>').append(
                            $('<input type="text">').attr('id','dateStart'+i).attr('class','dateStart'),
                            $('<br>'),
                            $('<input type="text">').attr('id','dateEnd'+i).attr('class','dateEnd')
                        );
            };
            function confirmedDataCell(){
                return $('<td>').append(
                            $('<input type="checkbox">').attr('id','confirmed'+i).attr('class','confirmed')    
                       );
            };
            
            function closeCheckBox(){
                return  $('<td>').append(
                      $('<a>').attr('id','isClosed'+i).attr('class','isClosed').text('Открыть')
                );
            };
            function deleteButton(){
                return $('<td>').append(
                    $('<input type="button">').attr('class','deleteDiseaseNote').attr('value','Удалить').button()
                );
            };
        </script>
    </div>
</div>
